"""
Copyright (c) 2024 [XKW.Beijing]
All rights reserved.

Author: [tangxiaojun]
Email: [417281862@qq.com]

"""
from flask import Flask, jsonify, make_response
from werkzeug.exceptions import HTTPException
from common_response import ResponseDto


def register_error_handlers(app: Flask):
    @app.errorhandler(404)
    def handle_404_error(e):
        response_data = ResponseDto(404, "", "Page Not Found").to_dict()
        return make_response(jsonify(response_data), 404)

    @app.errorhandler(Exception)
    def handle_500_error(e):
        if isinstance(e, HTTPException):
            return e
        return "Internal Server Error", 500

    @app.errorhandler(HTTPException)
    def handle_exception(e):
        response = e.get_response()
        data = {
            "code": e.code,
            "name": e.name,
            "description": e.description,
        }
        response_data = {
            "code": 500,
            "data": data,
            "message": "ServerError",
        }
        return make_response(jsonify(response_data), 404)
